document.addEventListener('DOMContentLoaded', function() {
  const startBtn = document.getElementById('startBtn');
  const stopBtn = document.getElementById('stopBtn');
  const status = document.getElementById('status');
  const dateModeSwitch = document.getElementById('dateModeSwitch');
  
  // 加载保存的日期模式设置
  chrome.storage.sync.get(['dateModeEnabled'], function(result) {
    dateModeSwitch.checked = result.dateModeEnabled !== false; // 默认为true
  });

  // 日期模式开关变化事件
  dateModeSwitch.addEventListener('change', function() {
    chrome.storage.sync.set({
      dateModeEnabled: dateModeSwitch.checked
    }, function() {
      console.log('日期模式设置已保存:', dateModeSwitch.checked);
    });
  });

  // 检查当前页面是否为Bing，并获取当前状态
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    const currentTab = tabs[0];
    const isBingPage = currentTab.url.includes('cn.bing.com') || currentTab.url.includes('bing.com');
    
    if (!isBingPage) {
      showStatus('请先访问 https://cn.bing.com/', 'error');
      startBtn.disabled = true;
    } else {
      // 检查是否有正在运行的搜索
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'getStatus'
      }, function(response) {
        if (chrome.runtime.lastError) {
          showStatus('检测到Bing页面，可以开始自动化', 'success');
          return;
        }
        
        if (response && response.isRunning) {
          const keywordInfo = response.keywordStats ? 
            ` | 关键词: ${response.keywordStats.used}/${response.keywordStats.total}` : '';
          const modeInfo = response.dateModeEnabled ? '日期模式' : '固定模式';
          showStatus(`搜索进行中: ${response.searchCount}/${response.maxSearches} 次${keywordInfo} | ${modeInfo}`, 'info');
          startBtn.disabled = true;
          stopBtn.disabled = false;
          
          // 同步开关状态
          dateModeSwitch.checked = response.dateModeEnabled;
        } else {
          showStatus('检测到Bing页面，可以开始自动化', 'success');
        }
      });
    }
  });
  
  // 开始按钮点击事件
  startBtn.addEventListener('click', function() {
    startBtn.disabled = true;
    stopBtn.disabled = false;
    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'executeAction',
        dateModeEnabled: dateModeSwitch.checked
      }, function(response) {
        if (chrome.runtime.lastError) {
          showStatus('无法连接到页面脚本，请刷新页面后重试', 'error');
          startBtn.disabled = false;
          stopBtn.disabled = true;
          return;
        }
        
        if (response && response.success) {
          showStatus(response.message || '自动化脚本已启动', 'success');
        } else {
          showStatus(response ? response.message : '启动失败', 'error');
          startBtn.disabled = false;
          stopBtn.disabled = true;
        }
      });
    });
  });
  
  // 停止按钮点击事件
  stopBtn.addEventListener('click', function() {
    startBtn.disabled = false;
    stopBtn.disabled = true;
    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'stopAction'
      }, function(response) {
        if (response && response.success) {
          showStatus(response.message || '自动化脚本已停止', 'info');
        } else {
          showStatus('停止操作可能未成功', 'error');
        }
      });
    });
  });
  
  // 显示状态信息
  function showStatus(message, type) {
    status.textContent = message;
    status.className = 'status ' + type;
    status.style.display = 'block';
    
    // 5秒后隐藏状态信息（除了错误信息）
    if (type !== 'error') {
      setTimeout(() => {
        status.style.display = 'none';
      }, 5000);
    }
  }
});